import random
import logging
from rest_framework import generics, status
from rest_framework.response import Response
from django.contrib.auth import get_user_model
from .serializers import RegisterSerializer, LoginSerializer, UserInfoSerializer, LogoutSerializer
from .tasks import send_code
from rest_framework.exceptions import ValidationError
from django_redis import get_redis_connection
from rest_framework.permissions import AllowAny, IsAuthenticated
from rest_framework.decorators import api_view, permission_classes
User = get_user_model()
logger = logging.getLogger('myproject')


class LoginView(generics.GenericAPIView):
    """
    用户登录视图
    支持使用用户名密码或手机号验证码登录
    """
    serializer_class = LoginSerializer
    permission_classes = [AllowAny]

    def post(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        try:
            serializer.is_valid(raise_exception=True)
            tokens = serializer.save()
            return Response({
                'message': '登录成功',
                'tokens': tokens
            }, status=status.HTTP_200_OK)
        except ValidationError as e:
            error_messages = []
            for field, errors in e.detail.items():
                error_messages.extend(errors)
            # 将错误信息数组合并为单个字符串
            error_message = ' '.join(error_messages)
            return Response({
                'message': error_message
            }, status=status.HTTP_400_BAD_REQUEST)


class LogoutView(generics.GenericAPIView):
    """
    用户登出视图
    将刷新 Token 加入黑名单
    """
    serializer_class = LogoutSerializer
    permission_classes = [IsAuthenticated]

    def post(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()

        return Response({"message": "登出成功"}, status=status.HTTP_200_OK)


class UserInfoView(generics.RetrieveAPIView):
    """
    获取当前认证用户的信息
    """
    serializer_class = UserInfoSerializer
    permission_classes = [IsAuthenticated]

    def get_object(self):
        return self.request.user


class RegisterView(generics.CreateAPIView):
    """
    用户注册视图
    """
    queryset = User.objects.all()
    serializer_class = RegisterSerializer

    def create(self, request, *args, **kwargs):
        phone = request.data.get('phone')
        verify_code = request.data.get('verify_code')

        if not phone:
            return Response({"message": "手机号是必需的"}, status=status.HTTP_400_BAD_REQUEST)
        if not verify_code:
            return Response({"message": "验证码是必需的"}, status=status.HTTP_400_BAD_REQUEST)

        # 从缓存中获取验证码
        # redis_conn = get_redis_connection("verify_code")
        # cached_code = redis_conn.get(f"verify_code_{phone}")
        # if not cached_code:
        #     return Response({"message": "验证码已过期或未发送"}, status=status.HTTP_400_BAD_REQUEST)
        # if verify_code != cached_code.decode('utf-8'):
        #     return Response({"message": "验证码错误"}, status=status.HTTP_400_BAD_REQUEST)

        # 调用父类的 create 方法进行用户创建
        response = super().create(request, *args, **kwargs)

        # 返回自定义的成功响应
        return Response({
            "message": "注册成功!",
            "username": response.data.get('username')
        }, status=status.HTTP_200_OK)


class SendVerifyCodeView(generics.GenericAPIView):
    """
    发送验证码视图
    """
    def post(self, request, *args, **kwargs):
        phone = request.data.get('phone')
        if not phone:
            return Response({"phone": "手机号不能为空"}, status=status.HTTP_400_BAD_REQUEST)
        verify_code = str(random.randint(100000, 999999))
        message = f"您的验证码是：{verify_code}。请不要把验证码泄露给其他人。"
        try:
            # 异步发送短信
            # send_code.delay(message, phone)
            redis_conn = get_redis_connection("verify_code")
            redis_conn.setex(f"verify_code_{phone}", 60, verify_code)
            return Response({"message": "验证码发送成功!"}, status=status.HTTP_200_OK)
        except Exception as e:
            logger.error(f"Error sending SMS: {e}")
            return Response({"error": "验证码发送失败！"}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


# 测试已经登录的用户信息，在认证参数中除了添加token信息还需要添加@api_view(['GET'])装饰器
@api_view(['GET'])
@permission_classes([IsAuthenticated])
def user_profile(request):
    user = request.user
    return Response({
        'id': user.id,
        'username': user.username,
        'email': user.email,
    })
